<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="帮助标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入帮助标题"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="分类" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择分类"
          clearable
          style="width: 180px"
        >
          <el-option label="全部" :value="-1" />
          <el-option label="充值" :value="0" />
          <el-option label="使用" :value="1" />
          <el-option label="账户" :value="2" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="helpList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="编号" prop="id" width="80" />
      <el-table-column label="帮助标题" prop="title" />

      <!-- 图片显示 -->
      <el-table-column label="图片" prop="images" width="150">
        <template #default="scope">
          <el-image
            v-for="(img, i) in scope.row.images"
            :key="i"
            :src="img"
            style="width: 40px; height: 40px; margin-right: 4px"
            :preview-src-list="scope.row.images"
          />
        </template>
      </el-table-column>

      <el-table-column label="分类" prop="type" width="100">
        <template #default="scope">
          {{
            scope.row.type === 0
              ? "充值"
              : scope.row.type === 1
              ? "使用"
              : scope.row.type === 2
              ? "账户"
              : "未知"
          }}
        </template>
      </el-table-column>

      <el-table-column label="内容" prop="content" show-overflow-tooltip />
      <el-table-column label="更新时间" prop="updateTime" width="160">
        <template #default="scope">
          {{ parseTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
<el-table-column label="是否上架" width="120">
  <template #default="scope">
    <el-switch
      v-model="scope.row.status"
      :active-value="1"
      :inactive-value="0"
      @change="(val) => handleStatusChange(scope.row)"
    ></el-switch>
  </template>
</el-table-column>

      <el-table-column label="创建时间" prop="createTime" width="160">
        <template #default="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
          ></el-button>
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.size"
      @pagination="getList"
    />

    <!-- 新增/修改弹窗 -->
    <el-dialog :title="title" v-model="open" width="650px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="90px">
        <el-form-item label="帮助标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入帮助标题" />
        </el-form-item>

        <el-form-item label="帮助内容" prop="content">
          <el-input
            type="textarea"
            :rows="4"
            v-model="form.content"
            placeholder="请输入帮助内容"
          />
        </el-form-item>

        <!-- 图片上传 -->
        <el-form-item label="图片">
          <el-upload
            class="upload-demo"
            action="/user/file/oss/upload"
            :headers="uploadHeaders"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :on-remove="handleUploadRemove"
            :before-upload="beforeUpload"
            :file-list="fileList"
            name="file"
            :data="{ dir: 'admin' }"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img width="100%" :src="dialogImageUrl" />
          </el-dialog>
        </el-form-item>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="分类" prop="type">
              <el-select v-model="form.type">
                <el-option label="充值" :value="0" />
                <el-option label="使用" :value="1" />
                <el-option label="账户" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" :max="9999" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="HelpCenter">
import {
  listHelpCenter,
  addHelpCenter,
  updateHelpCenter,
  delHelpCenter,
  getHelpCenter,activeHelpCenter 
} from "@/api/system/helpcenter";

import { ref, reactive, toRefs, getCurrentInstance } from "vue";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";

const { proxy } = getCurrentInstance();

const helpList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
import { getToken } from "@/utils/auth";

const uploadHeaders = ref({
  "Authorization-Admin": getToken()
});



// 表单图片数组（提交给后端）
const imageList = ref([]);
// 上传组件显示用
const fileList = ref([]);

const data = reactive({
  form: {
    id: undefined,
    title: "",
    content: "",
    type: 0,
    sort: 0,
    images: [],
  },
  queryParams: {
    title: "",
    type: -1,
    page: 1,
    size: 10,
  },
  rules: {
    title: [{ required: true, message: "帮助标题不能为空", trigger: "blur" }],
    content: [{ required: true, message: "帮助内容不能为空", trigger: "blur" }],
    type: [{ required: true, message: "分类不能为空", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 上传前验证 */
const beforeUpload = (file) => {
  if (!file.type.startsWith("image/")) {
    proxy.$modal.msgError("只能上传图片！");
    return false;
  }
  return true;
};

/** 上传成功写入 imageList */
const handleUploadSuccess = (res, file, fileListNow) => {
  if (res.code === 200 || res.code === 0) {
    const url = res.data.url;
    imageList.value.push(url);

    fileList.value = fileListNow.map((f) => ({
      name: f.name,
      url: f.response ? f.response.data.url : f.url,
    }));
  }
};

/** 删除图片 */
const handleUploadRemove = (file, fileListNow) => {
  const url = file.url || file.response?.data.url;
  imageList.value = imageList.value.filter((x) => x !== url);

  fileList.value = fileListNow.map((f) => ({
    name: f.name,
    url: f.url,
  }));
};

/** 获取列表 */
function getList() {
  loading.value = true;
  listHelpCenter(queryParams.value)
    .then((res) => {
      helpList.value = res.data.records;
      total.value = Number(res.data.total) || 0;

      helpList.value.forEach((item) => {
        if (typeof item.images === "string") {
          item.images = item.images.split(",");
        }
      });
    })
    .finally(() => (loading.value = false));
}

/** 搜索 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}

/** 重置 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.type = -1;
  handleQuery();
}

/** 多选框 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 重置表单 */
function reset() {
  form.value = {
    id: undefined,
    title: "",
    content: "",
    type: 0,
    sort: 0,
    images: [],
  };
  imageList.value = [];
  fileList.value = [];
  proxy.resetForm("userRef");
}

/** 取消 */
function cancel() {
  open.value = false;
  reset();
}

/** 新增 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增帮助信息";
}

/** 修改 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value[0];

  getHelpCenter(id).then((res) => {
    form.value = res.data;

    const arr =
      typeof form.value.images === "string"
        ? form.value.images.split(",")
        : form.value.images || [];

    imageList.value = arr;
    fileList.value = arr.map((url) => ({
      name: url.substring(url.lastIndexOf("/") + 1),
      url,
    }));

    open.value = true;
    title.value = "修改帮助信息";
  });
}

/** 删除 */
function handleDelete(row) {
  const delIds = row.id || ids.value;
  proxy.$modal
    .confirm(`确认删除编号为 "${delIds}" 的帮助信息？`)
    .then(() => delHelpCenter(delIds))
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
      getList();
    });
}

/** 提交 */
function submitForm() {
  proxy.$refs["userRef"].validate((valid) => {
    if (!valid) return;

    form.value.images = imageList.value;

    if (form.value.id) {
      updateHelpCenter(form.value).then(() => {
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        getList();
      });
    } else {
      addHelpCenter(form.value).then(() => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
    }
  });
}

async function handleStatusChange(row) {
  const text = row.status === 1 ? "上架" : "下架";

  try {
    await proxy.$modal.confirm(`确认要${text}该帮助 "${row.title}" 吗？`);
    
    const res = await activeHelpCenter(row.id, row.status); // 调用接口
    if (res.code === 0 || res.code === 200) {
      proxy.$modal.msgSuccess(`${text}成功`);
    } else {
      throw new Error(res.msg || "接口错误");
    }
  } catch (err) {
    // 回滚状态
    row.status = row.status === 1 ? 0 : 1;
  }
}
getList();
</script>
